#!/usr/bin/env python3
"""
ESP32扩展板引脚配置工具
帮助用户根据实际硬件连接快速配置引脚
"""

import os
import sys

def get_pin_config():
    """获取用户的引脚配置"""
    print("=== ESP32扩展板引脚配置工具 ===")
    print("请根据您的实际硬件连接输入引脚号")
    print("(直接按回车使用默认值)")
    print()
    
    config = {}
    
    # ADC传感器引脚
    print("ADC传感器引脚配置 (自选做ADC区域):")
    config['TEMP_SENSOR_PIN'] = input("温度传感器引脚 [默认: 36]: ").strip() or "36"
    config['HUMID_SENSOR_PIN'] = input("湿度传感器引脚 [默认: 39]: ").strip() or "39"
    
    # GPIO数字引脚
    print("\nGPIO数字引脚配置 (GPIO区域):")
    config['LED_PIN'] = input("LED指示灯引脚 [默认: 2]: ").strip() or "2"
    config['BUTTON_PIN'] = input("按钮开关引脚 [默认: 0]: ").strip() or "0"
    config['RELAY_PIN'] = input("继电器控制引脚 [默认: 4]: ").strip() or "4"
    
    # I2C引脚
    print("\nI2C引脚配置 (自选做IIC区域) - 预留扩展:")
    config['I2C_SDA_PIN'] = input("I2C数据线引脚 [默认: 21]: ").strip() or "21"
    config['I2C_SCL_PIN'] = input("I2C时钟线引脚 [默认: 22]: ").strip() or "22"
    
    return config

def generate_pin_config_file(config):
    """生成引脚配置文件"""
    
    # ADC通道映射
    adc_mapping = {
        "36": "ADC1_CHANNEL_0",
        "37": "ADC1_CHANNEL_1", 
        "38": "ADC1_CHANNEL_2",
        "39": "ADC1_CHANNEL_3",
        "32": "ADC1_CHANNEL_4",
        "33": "ADC1_CHANNEL_5",
        "34": "ADC1_CHANNEL_6",
        "35": "ADC1_CHANNEL_7"
    }
    
    temp_adc = adc_mapping.get(config['TEMP_SENSOR_PIN'], "ADC1_CHANNEL_0")
    humid_adc = adc_mapping.get(config['HUMID_SENSOR_PIN'], "ADC1_CHANNEL_3")
    
    content = f"""/*
 * ESP32 扩展板引脚配置
 * 此文件由配置工具自动生成
 * 生成时间: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
 */

#ifndef PIN_CONFIG_H
#define PIN_CONFIG_H

// ===========================================
// ADC传感器引脚 (自选做ADC区域)
// ===========================================
#define TEMP_SENSOR_PIN {config['TEMP_SENSOR_PIN']}    // 温度传感器ADC引脚
#define HUMID_SENSOR_PIN {config['HUMID_SENSOR_PIN']}   // 湿度传感器ADC引脚

// 对应的ADC通道
#define TEMP_ADC_CHANNEL {temp_adc}   // GPIO{config['TEMP_SENSOR_PIN']}
#define HUMID_ADC_CHANNEL {humid_adc}  // GPIO{config['HUMID_SENSOR_PIN']}

// ===========================================
// GPIO数字引脚 (GPIO区域)
// ===========================================
#define LED_PIN {config['LED_PIN']}             // LED指示灯
#define BUTTON_PIN {config['BUTTON_PIN']}          // 按钮开关
#define RELAY_PIN {config['RELAY_PIN']}           // 继电器控制

// ===========================================
// I2C引脚 (自选做IIC区域) - 预留扩展
// ===========================================
#define I2C_SDA_PIN {config['I2C_SDA_PIN']}        // I2C数据线
#define I2C_SCL_PIN {config['I2C_SCL_PIN']}        // I2C时钟线

// ===========================================
// SPI引脚 (自选做SPI区域) - 预留扩展
// ===========================================
#define SPI_MOSI_PIN 23       // SPI主出从入
#define SPI_MISO_PIN 19       // SPI主入从出
#define SPI_SCK_PIN 18        // SPI时钟
#define SPI_CS_PIN 5          // SPI片选

#endif // PIN_CONFIG_H
"""
    
    return content

def save_config_file(content):
    """保存配置文件"""
    config_path = "../esp32_firmware/src/pin_config.h"
    
    try:
        with open(config_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"✅ 配置文件已保存到: {config_path}")
        return True
    except Exception as e:
        print(f"❌ 保存配置文件失败: {e}")
        return False

def show_summary(config):
    """显示配置摘要"""
    print("\n=== 配置摘要 ===")
    print("ADC传感器:")
    print(f"  温度传感器: GPIO{config['TEMP_SENSOR_PIN']}")
    print(f"  湿度传感器: GPIO{config['HUMID_SENSOR_PIN']}")
    print("GPIO设备:")
    print(f"  LED指示灯: GPIO{config['LED_PIN']}")
    print(f"  按钮开关: GPIO{config['BUTTON_PIN']}")
    print(f"  继电器: GPIO{config['RELAY_PIN']}")
    print("I2C接口:")
    print(f"  SDA数据线: GPIO{config['I2C_SDA_PIN']}")
    print(f"  SCL时钟线: GPIO{config['I2C_SCL_PIN']}")

def main():
    """主函数"""
    try:
        # 获取配置
        config = get_pin_config()
        
        # 显示摘要
        show_summary(config)
        
        # 确认保存
        print("\n是否保存此配置? (y/N): ", end="")
        confirm = input().strip().lower()
        
        if confirm == 'y':
            # 生成配置文件内容
            content = generate_pin_config_file(config)
            
            # 保存配置文件
            if save_config_file(content):
                print("\n✅ 配置完成!")
                print("下一步:")
                print("1. 根据配置连接硬件")
                print("2. 编译固件: cd ../esp32_firmware && pio run")
                print("3. 刷写固件: python3 flash_esp32.py --firmware ../esp32_firmware/.pio/build/esp32dev/firmware.bin")
            else:
                print("\n❌ 配置失败!")
                return 1
        else:
            print("配置已取消")
            
    except KeyboardInterrupt:
        print("\n\n配置已取消")
        return 1
    except Exception as e:
        print(f"\n❌ 配置过程中出错: {e}")
        return 1
    
    return 0

if __name__ == "__main__":
    sys.exit(main())